import { useEffect, useRef } from "preact/hooks";
import { settings, box } from "../settings";
import { findFavo } from "../signals";
import { stopPropagation } from "../utilities";
import { Globe, Star } from "lucide-preact";
import { themes, engines, checkEngine } from "../engines";

const LeftButton = ({ onSwap }) => {
  const popReference = useRef(null);
  useEffect(() => {
    const touchHide = () => {
      popReference.current?.hidePopover();
    };
    box.addEventListener("touchstart", touchHide);
    return () => box.removeEventListener("touchstart", touchHide);
  }, []);

  switch (settings.value.searchPart.leftButton) {
    case 0: {
      return <div class="px-1" />;
    }
    case 1: {
      return (
        <label class="swap swap-rotate ml-1 p-2">
          <input
            type="checkbox"
            checked={findFavo}
            onChange={(event) => {
              findFavo.value = event.target.checked;
              onSwap();
            }}
          />
          <Globe class="swap-off size-5" />
          <Star class="swap-on size-5" />
        </label>
      );
    }
    case 2: {
      return (
        <>
          <button
            type="button"
            class="ml-1 appearance-none p-2"
            onClick={() => {
              popReference.current?.togglePopover();
            }}
            onTouchStart={stopPropagation}
            style={{ anchorName: "--ebtn-anchor" }}
          >
            <Globe class="size-5" />
          </button>
          <div
            class="dropdown dropdown-center card card-xs rounded-box m-1"
            popover="manual"
            ref={popReference}
            style={{ positionAnchor: "--ebtn-anchor" }}
            onTouchStart={stopPropagation}
          >
            {engines.value.map((engine) => (
              <button
                type="button"
                class={`btn btn-sm rounded-[0] ${engine.checked ? `btn-soft ${themes[engine.theme][0]}` : "btn-ghost"}`}
                onClick={() => {
                  checkEngine(engine.name);
                  popReference.current?.hidePopover();
                }}
                key={engine.name}
              >
                {engine.name}
              </button>
            ))}
          </div>
        </>
      );
    }
  }
};

export default LeftButton;
